//
//  CategoryTypeView.swift
//  KoiPrototype2
//
//  Created by 纪洪文 on 06.03.25.
//

import SwiftUI

struct KoiTabBar<SelectionValue: Hashable> : View {
    
    @Binding var selection: SelectionValue
    var items: Array<TabBarItem<SelectionValue>>
    
    var body: some View {
        HStack {
            ForEach(items.indices, id:\.self) { index in
                Button(action: {
                    selection = items[index].tab
                }) {
                    if (items[index].isLarge) {
                        TabBarItemView(item: items[index], isSelected: items[index].tab == selection)
                            .frame(maxWidth: .infinity)
                    } else {
                        TabBarItemView(item: items[index], isSelected: items[index].tab == selection)
                    }
                }
            }
        }
        .padding(EdgeInsets(top: 2, leading: 2, bottom: 2, trailing: 2))
        .background(Color.koiColorBackgroundItem)
        .cornerRadius(50)
            
    }
    
    private func textForegroundColor(selected: Bool) -> Color {
        return selected ? Color.koiColorTitle : Color.koiColorTitleSecond
    }
    
    private func textBackground(selected: Bool) -> Color {
        return selected ? Color.white : Color.white.opacity(0)
    }
}

struct TabBarItem<SelectionValue : Hashable> {
    var tab: SelectionValue
    var name: String
    var isLarge = false
}

struct TabBarItemView<SelectionValue : Hashable> : View {
    var item: TabBarItem<SelectionValue>
    var isSelected = false

    
    var body: some View {
        if (item.isLarge) {
            Text(item.name)
                .font(.system(size: 14))
                .bold()
                .foregroundColor(textForegroundColor(selected: isSelected))
                .padding(EdgeInsets(top: 8, leading: 20, bottom: 8, trailing: 20))
                .frame(maxWidth: .infinity)
                .background(textBackground(selected: isSelected))
                .cornerRadius(40)
        } else {
            Text(item.name)
                .font(.system(size: 14))
                .bold()
                .foregroundColor(textForegroundColor(selected: isSelected))
                .padding(EdgeInsets(top: 8, leading: 20, bottom: 8, trailing: 20))
                .background(textBackground(selected: isSelected))
                .cornerRadius(40)
        }
    }
    
    private func textForegroundColor(selected: Bool) -> Color {
        return selected ? Color.koiColorTitle : Color.koiColorTitleSecond
    }
    
    private func textBackground(selected: Bool) -> Color {
        return selected ? Color.white : Color.white.opacity(0)
    }
}
